from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import memoize
from Acquisition import aq_inner
from zope.i18n.interfaces import ITranslationDomain
from zope.component import queryUtility
from my315ok.xtjxwcontents.interfaces.jiaolian import Ijiaolian
from my315ok.xtjxwcontents.interfaces import Ijiaxiaoimage
from Products.ATContentTypes.interface.document import IATDocument
#from Products.ATContentTypes.interfaces import IATImage

from my315ok.xtjxwcontents import xtjxwcontentsMessageFactory as _


class IjiaxiaoView(Interface):
    """
    jiaxiao view interface
    """




class jiaxiaoView(BrowserView):
    """
    jiaxiao browser view
    """
    implements(IjiaxiaoView)

    def __init__(self, context, request):
        self.context = context
        self.request = request

    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def portal(self):
        return getToolByName(self.context, 'portal_url').getPortalObject()


    @memoize
    def translates(self,item):
#        import pdb
#        pdb.set_trace()      
        
        util = queryUtility(ITranslationDomain, 'my315ok.xtjxwcontents')    
        tted = util.translate(item,target_language="zh",
                                       default="xiangtanshihexi")           
        return tted
    
    @memoize
    def map(self):
        """render the map of the house position"""
        
        name = self.translates(self.context.getDistrict())
        out = """jq(document).ready(function initialize() {var myLatlng = new google.maps.LatLng(%s,%s);
        var myOptions = {
        zoom: 12,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        };
       var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
       var contentString = '<div id="map-mark">' + 
       '<a target="_blank" href="#">%s</a>' + '</div><br />' +
       '<span>%s</span>';
       var infowindow = new google.maps.InfoWindow({content: contentString});
       var marker = new google.maps.Marker({position: myLatlng,map: map,title:"%s"});
       infowindow.open(map,marker);    
       })""" % (self.context.getLatitude(),self.context.getLongitude(),name,self.context.getName(),name)
        return out
#       jq('body').bind('onload',initialize())    
    @memoize
    def image(self):
        """fetch house main photo"""
        
        alt = self.context.Title()
        p_url = self.portal.absolute_url()
        try:
            photo = self.fetchjiaxiaoimage()
            sc = photo.getURL() + '/image'
        except:              
            sc = p_url + "/++resource++schoolwatermark.png"            
        html='<img src="%s" alt="%s" />' % (sc,alt)
        return html
    
    @memoize
    def addfav(self):
        """<a onclick="javascript:window.external.AddFavorite('http://www.07312s.com/sale/d-2254.html',
        ' test');
        return false;" href="http://www.07312s.com/sale/d-2254.html" class="color690">shoucang</a>"""
        url = self.context.absolute_url()
        title = self.context.Title()
        out ="javascript:window.external.AddFavorite('%s','%s');return false;" % (url,title)
        return out
    
    @memoize
    def fetchjiaolian(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        sepath= '/'.join(context.getPhysicalPath()) 
#        catalog = getToolByName(self.context, 'portal_catalog')        
#        sepath = '/'.join(self.context.getPhysicalPath()) 
        query = {'object_provides':Ijiaolian.__identifier__,
                 'sort_on':'modified',
                 'sort_order':'reverse',
                 'path':sepath,
         'level':1,
                 }        
        sd = catalog(query)
        return sd
    
    def jiaolianinfo(self,scale="thumb"):
        brain = self.fetchjiaolian()
        infos = []
        info = {}
        for bn in brain:
            info['name'] = bn.name
            tl = bn.Title
            ul = bn.getURL()
            info['url'] = ul            
            src = ul + '/image_' + scale
            img = '<img src="%s" alt ="%s" />' %(src,tl)
            info['img'] = img
            del tl,src,img
            infos.append(info)
        return infos 
            
            
    @memoize
    def fetchfaq(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        sepath= '/'.join(context.getPhysicalPath()) 
#        catalog = getToolByName(self.context, 'portal_catalog')        
#        sepath = '/'.join(self.context.getPhysicalPath()) 
        query = {'object_provides':IATDocument.__identifier__,
                 'path':sepath,
         'level':1,
                 }        
        sd = catalog(query)
        if len(sd) > 0:
            return sd[0].getObject().getText()
        else:
            return ""
            

    
#    @memoize
#    def fetchimage(self):
#        context = aq_inner(self.context)
#        catalog = getToolByName(context, 'portal_catalog')
#        sepath= '/'.join(context.getPhysicalPath()) 
##        catalog = getToolByName(self.context, 'portal_catalog')        
##        sepath = '/'.join(self.context.getPhysicalPath()) 
#        query = {'object_provides':IATImage.__identifier__,
#                 'sort_on':'getObjPositionInParent',
#                 'sort_order':'forward',
#                 'path':sepath,
#         'level':1,
#                 }        
#        sd = catalog(query)
#        return sd
    
    @memoize
    def render_marqueejs(self,vname,topid,cssid,showtext):
        url = self.context.absolute_url()
        imgsrc = url + '/' + vname
#        topid = 'roll_chanpin'
#        cssid = '.roll_image'
#        showtext = 1  
        out="""jq(document).ready(function(){ajaxfetchimg("%(topid)s","%(url)s",".%(mid)s",%(text)s);});""" % dict(topid=topid,url=imgsrc,mid=cssid,text=showtext)
#        out= out + """jq(".%(mid)s").mouseover(function(){marquee();});""" % dict(mid=cssid)

        return out          
    @memoize
    def fetchjiaxiaoimage(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        sepath= '/'.join(context.getPhysicalPath()) 
#        catalog = getToolByName(self.context, 'portal_catalog')        
#        sepath = '/'.join(self.context.getPhysicalPath()) 
        query = {'object_provides':Ijiaxiaoimage.__identifier__,
                 'sort_on':'modified',
                 'sort_order':'reverse',
                 'path':sepath,
                 'sort_limit':1,
         'level':1,
                 }        
        sd = catalog(query)[0]
        return sd       
    def test(self,a,b,c):
        if a:
            return b
        else:
            return c
 